# -*- coding: utf-8 -*-

import time
import random
import requests
from dbmovie.datasql import main

# User Agent
UA = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.2226.0 Safari/537.36"

# HTTP 请求头
headers = {
    "Host": "api.douban.com",
    "User-Agent": UA
}


class Singleton(object):
    """
        实现单例模式，Crawl在程序中只有一个实例

        Attributes:
            _instance: 唯一实例的引用。
    """
    _instance = None

    def __new__(cls, *args, **kw):
        if not cls._instance:
            cls._instance = super(Singleton, cls).__new__(cls, *args, **kw)
        return cls._instance


class Crawl(Singleton):
    """
        :start 页码,以20为倍数
    """

    def __init__(self):
        pass

    def __getpagejson(self):

        datas = []
        for start in range(0, 20, 20):
            data = []
            data_url = 'http://api.douban.com/v2/movie/top250?start={}'.format(start)  # 豆瓣电影top250API
            response = requests.get(data_url, headers=headers)
            response.encoding = 'utf-8'
            print(response.text)
            print('-*-*'*20)
            time.sleep(random.randint(15, 60))
            if response.status_code != 200:
                print(response.status_code)
                break
            else:
                try:
                    data.append(response.json()['subjects'][0])
                    datas = datas + data
                    print(datas)
                except Exception as e:
                    print(e)

        return datas

    def getinfo(self):

        datas = []
        for info in self.__getpagejson():

            infos = {}

            infos['average'] = info['rating']['average']  # 评分
            infos['stars'] = info['rating']['stars']  # 星星等级
            infos['genres'] = ','.join(info['genres'])  # 类型
            infos['title'] = info['title']  # 电影名
            infos['avatars'] = ','.join([a['name'] for a in info['casts']])  # 主演
            infos['original_title'] = info['original_title']    # 原名
            infos['directors'] = info['directors'][0]['name']    # 导演
            infos['year'] = info['year']    # 年份

            main(infos)
            datas.append(infos)
            print('*-*-'*20)
            print(infos)

        return datas


if __name__ == '__main__':

    s = Crawl()
    a = s.getinfo()





